import requests
import re
import json
import csv


# 发送请求
url = 'https://voice.baidu.com/act/newpneumonia/newpneumonia/?from=osari_aladin_banner'
response = requests.get(url=url)

# 数据解析
data_html = response.text

# 正则转换数据类型从list到str
json_str = re.findall('"component":\[(.*)\],', data_html)[0]

# 转换字典
json_dict = json.loads(json_str)
caseList = json_dict['caseList']

for case in caseList:
    area = case['area']
    confirmed = case['confirmed']
    curConfirm = case['curConfirm']
    asymptomatic = case['asymptomatic']
    crued = case['crued']
    died = case['died']
    confirmedRelative = case['confirmedRelative']
    diedRelative = case['diedRelative']
    curedRelative = case['curedRelative']
    asymptomaticRelative = case['asymptomaticRelative']
    nativeRelative = case['nativeRelative']
    overseasInputRelative = case['overseasInputRelative']

# 保存成csv
with open('./data.csv', mode='a', encoding='utf-8', newline='')as f:
        csv_writer = csv.writer(f)
        # 疫情地区、新增、现有、累计、治愈、死亡
        csv_writer.writerow([area, confirmedRelative, curConfirm, confirmed, crued, died])
